﻿using System;
using System.Web.UI.WebControls;
using br.com.SistemaChamados.Constants;
using br.com.SistemaChamados.Controller;
using br.com.SistemaChamados.Enum;
using br.com.SistemaChamados.Model;
using System.Web.Security;
using br.com.SistemaChamados.Controller.Common;
using br.com.SistemaChamados.Util;

public partial class Pages_PlaceUpdate : System.Web.UI.Page
{
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        ViewStateUserKey = Session.SessionID;
    }

    protected void Page_PreInit(object sender, EventArgs e)
    {
        br.com.SistemaChamados.Model.Common.User loggedUser = new br.com.SistemaChamados.Model.Common.User();
        UserController userController = new UserController();
        if (Session[UserConstants.SESSION_USER_LOGGED_IN] != null)
        {
            loggedUser.Id = Convert.ToInt32(Session[UserConstants.SESSION_USER_LOGGED_IN]);
            loggedUser = userController.GetUser(loggedUser);
            this.MasterPageFile = MasterPageDefiner.defineMasterPageByAccessRole(loggedUser.Profile);
            ((Label)Master.FindControl("lblUser")).Text = loggedUser.Name;
            this.Title = "SysCall - Sistema de chamados [logado como " + loggedUser.Name + "]";
        }
        else
        {
            Response.Redirect("~/Pages/Login/Login.aspx");
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!User.IsInRole("ADMIN"))
        {
            if (!IsPostBack)
            {
                FillDdlState();
                FillData();
            }
        }
        else
        {
            FormsAuthentication.SignOut();
            Response.Clear();
            Response.Redirect("~/Pages/Login/Login.aspx");
        }
    }

    private void FillDdlState()
    {
        StateController stateController = new StateController();
        ddlState.DataSource = stateController.GetStates();
        ddlState.DataTextField = "Acronym";
        ddlState.DataValueField = "Id";
        ddlState.DataBind();
        ddlState.Items.Insert(0, "Selecione");
    }

    private void FillDdlCity()
    {
        CityController cityController = new CityController();
        State state = new State();
        if (Convert.ToInt32(ddlState.SelectedIndex) != 0)
        {
            state.Id = Convert.ToInt32(ddlState.SelectedValue);
            ddlCity.DataSource = cityController.listCityByState(state);
            ddlCity.DataTextField = "Description";
            ddlCity.DataValueField = "Id";
            ddlCity.DataBind();
            ddlCity.Items.Insert(0, "Selecione");
        }
        else
        {
            ClearDdlCity();
        }
    }

    private void FillData()
    {
        string id = Session[PlaceConstants.SESSION_PLACE_ID].ToString();
        Place place = new Place();
        PlaceController placeController = new PlaceController();
        place.Id = Convert.ToInt32(id);
        place = placeController.GetPlace(Convert.ToInt32(id));
        City city = new City();
        CityController cityController = new CityController();
        city.Id = place.City.Id;
        city = cityController.SelectCity(city);
        try
        {
            MatchDdlStateValue(city);
            FillDdlCity();
            MatchDdlCityValue(city);
            txbAddress.Text = Convert.ToString(place.Address);
            txbComplement.Text = Convert.ToString(place.Complement);
            txbNumber.Text = Convert.ToString(place.Number);
            txbZip.Text = Convert.ToString(place.ZipCode);
            txbDescription.Text = place.Description;
        }
        catch (Exception ex)
        {
            Response.Write(@"<script language='javascript'>alert('Ocorreu um erro na carga dos valores: <br>" + ex.Message +
                               ".');</script>");
        }
    }

    private void MatchDdlStateValue(City city)
    {
        ListItem listState = ddlState.Items.FindByValue(Convert.ToString(city.State.Id));

        for (int i = 0; i < ddlState.Items.Count; i++)
        {
            ddlState.Items[i].Selected = false;
        }
        if (listState != null)
        {
            listState.Selected = true;
        }
        else
        {
            ddlState.Items[0].Selected = true;
        }
    }

    private void MatchDdlCityValue(City city)
    {
        ListItem listCity = ddlCity.Items.FindByValue(Convert.ToString(city.Id));
        for (int i = 0; i < ddlCity.Items.Count; i++)
        {
            ddlCity.Items[i].Selected = false;
        }
        if (listCity != null)
        {
            listCity.Selected = true;
        }
        else
        {
            ddlCity.Items[0].Selected = true;
        }
    }

    private void ClearFields()
    {
        txbAddress.Text = "";
        txbComplement.Text = "";
        txbZip.Text = "";
        txbNumber.Text = "";
        for (int i = 0; i < ddlState.Items.Count; i++)
        {
            ddlState.Items[i].Selected = false;
        }
        ddlState.Items[0].Selected = true;

    }

    private void ClearDdlCity()
    {
        for (int i = 0; i < ddlCity.Items.Count; i++)
        {
            ddlCity.Items[i].Selected = false;
        }
        ddlCity.Items[0].Selected = true;
        ddlCity.DataSource = "";
        ddlCity.DataBind();
    }

    protected void ddlState_SelectedIndexChanged(object sender, EventArgs e)
    {
        FillDdlCity();
    }

    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        Place place = new Place();
        PlaceController placeController = new PlaceController();
        City city = null;
        try
        {
            city = createCityToUpdate(place, city);
            EnumCRUDState resultOperation = placeController.UpdatePlace(place);
            if (resultOperation == EnumCRUDState.SQL_SUCCESS)
            {
                Response.Write(@"<script language='javascript'>alert('Local alterado com sucesso!');</script>");
                Response.Redirect("PlaceMain.aspx");
            }
            else
            {
                Response.Write(@"<script language='javascript'>alert('Ocorreu um erro durante a alteração, por favor tente novamente!');</script>");
            }
        }
        catch (Exception ex)
        {
            Response.Write(@"<script language='javascript'>alert('Ocorreu um erro ao alterar o local: <br>" + ex.Message + ".');</script>");
            place = null;
            placeController = null;
        }
        finally
        {
            Session.Remove(PlaceConstants.SESSION_PLACE_ID);
        }
    }

    private City createCityToUpdate(Place place, City city)
    {
        city = new City();
        city.Id = Convert.ToInt32(ddlCity.SelectedValue);
        place.Id = Convert.ToInt32(Session[PlaceConstants.SESSION_PLACE_ID]);
        place.ZipCode = Convert.ToInt32(txbZip.Text);
        place.Address = Convert.ToString(txbAddress.Text);
        place.Complement = Convert.ToString(txbComplement.Text);
        place.Number = Convert.ToInt32(txbNumber.Text);
        place.City = city;
        place.Description = txbDescription.Text;
        return city;
    }
}